package edu.zut.hys.jsskateboard.util;

import edu.zut.hys.jsskateboard.StaticV;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.ace.ability.LocalParticleAbility;
import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.photokit.metadata.AVStorage;
import ohos.rpc.IRemoteObject;
import ohos.utils.net.Uri;

import java.io.*;

public class UtilServiceAbility extends Ability implements LocalParticleAbility {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
    private static final UtilServiceAbility INSTANCE = new UtilServiceAbility();

    public static LocalParticleAbility getInstance() {
        return INSTANCE;
    }

    public void CopyToCache(String path, Callback callback) throws IOException {
        HiLog.info(LABEL_LOG,"开始");
        DataAbilityHelper helper=DataAbilityHelper.creator(StaticV.context);
        HiLog.info(LABEL_LOG,"helper");
        String fileName = "EXCEPTION";
        //原始文件Uri
        Uri src = Uri.parse(path);
        HiLog.info(LABEL_LOG,"parse "+src);
        //通过DataAbilityHelper获取文件名与文件类型
        try {
            DataAbilityHelper pathHelper = DataAbilityHelper.creator(StaticV.context, src, false);
            ResultSet resultSet = pathHelper.query(src,null,null);
            HiLog.info(LABEL_LOG,"数量"+resultSet.getRowCount());
            resultSet.goToNextRow();
            String srcpath = resultSet.getString(resultSet.getColumnIndexForName(AVStorage.AVBaseColumns.DATA));
            HiLog.info(LABEL_LOG,"路径"+srcpath);
            String[] strings = srcpath.split("/");
            //文件名
            fileName = strings[strings.length-1];
            HiLog.info(LABEL_LOG,"文件名"+fileName);
            resultSet.close();
            pathHelper.release();
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }

        if(!fileName.equals("EXCEPTION")){
            FileDescriptor srcfd = null;
            try {
                //图库中文件的文件描述符
                srcfd = helper.openFile(src,"r");
            } catch (DataAbilityRemoteException e) {
                HiLog.info(LABEL_LOG,"srcfd erro "+e);
                e.printStackTrace();
            }
            //获取原始文件输入流
            FileInputStream srcfis = new FileInputStream(srcfd);
            HiLog.info(LABEL_LOG,"fis");

            String tarpath = StaticV.context.getCacheDir().getAbsolutePath();
            HiLog.info(LABEL_LOG,tarpath);
            //获取应用内部目录的文件输出流
            FileOutputStream fos = new FileOutputStream(tarpath+"/"+fileName);
            int length;
            byte[] buffer = new byte[1024];
            while((length = srcfis.read(buffer))!=-1){
                fos.write(buffer,0,length);
            }
            HiLog.info(LABEL_LOG,"写入完成");
            srcfis.close();
            fos.close();
            helper.release();

            callback.reply(fileName);
            File tarfile = new File(tarpath+"/"+fileName);
            HiLog.info(LABEL_LOG, String.valueOf(tarfile.isFile()));
        }
    }

    public void savePicture(String path, Callback callback) throws IOException {
        HiLog.info(LABEL_LOG,"开始"+StaticV.context.getCacheDir().getAbsolutePath());
        DataAbilityHelper helper=DataAbilityHelper.creator(StaticV.context);
        ValuesBucket values = new ValuesBucket();
        HiLog.info(LABEL_LOG,"helper");
        String[] paths = path.split("/");
        String res = paths[paths.length-1];

        HiLog.info(LABEL_LOG,StaticV.context.getCacheDir().getAbsolutePath()+"/"+res);
        FileInputStream srcfis = new FileInputStream(StaticV.context.getCacheDir().getAbsolutePath()+"/"+res);
        HiLog.info(LABEL_LOG,"fis");

        //待创建的文件名
        values.putString(AVStorage.Downloads.DISPLAY_NAME, res.split("\\.")[0]);
        //文件格式
        values.putString(AVStorage.Downloads.MIME_TYPE, "image/"+res.split("\\.")[1]);
        //向DataAbilityHelper中插入文件信息，插入成功后会返回文件的id
        try {
            int id = helper.insert(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, values);
            //通过id拼接文件的uri
            Uri targeruri = Uri.appendEncodedPathToUri(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
            FileDescriptor fd = helper.openFile(targeruri, "rw");
            FileOutputStream fos = new FileOutputStream(fd);
            HiLog.info(LABEL_LOG,"fos");
            int length;
            byte[] buffer = new byte[1024];
            while((length = srcfis.read(buffer))!=-1){
                fos.write(buffer,0,length);
            }
            HiLog.info(LABEL_LOG,"写入完成");
            fos.close();
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }

        srcfis.close();
        callback.reply(res);
    }

//    public void saveVideo(String path, Callback callback) throws IOException {
//        HiLog.info(LABEL_LOG,"开始"+StaticV.context.getCacheDir().getAbsolutePath());
//        DataAbilityHelper helper=DataAbilityHelper.creator(StaticV.context);
//        ValuesBucket values = new ValuesBucket();
//        HiLog.info(LABEL_LOG,"helper");
//        String[] paths = path.split("/");
//        String res = paths[paths.length-1];
//
//        HiLog.info(LABEL_LOG,StaticV.context.getCacheDir().getAbsolutePath()+"/"+res);
//        FileInputStream srcfis = new FileInputStream(StaticV.context.getCacheDir().getAbsolutePath()+"/"+res);
//        HiLog.info(LABEL_LOG,"fis");
//
//        //待创建的文件名
//        values.putString(AVStorage.Downloads.DISPLAY_NAME, res.split("\\.")[0]);
//        //文件格式
//        values.putString(AVStorage.Downloads.MIME_TYPE, "video/"+res.split("\\.")[1]);
//        //向DataAbilityHelper中插入文件信息，插入成功后会返回文件的id
//        try {
//            int id = helper.insert(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, values);
//            //通过id拼接文件的uri
//            Uri targeruri = Uri.appendEncodedPathToUri(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
//            FileDescriptor fd = helper.openFile(targeruri, "rw");
//            FileOutputStream fos = new FileOutputStream(fd);
//            HiLog.info(LABEL_LOG,"fos");
//            int length;
//            byte[] buffer = new byte[1024];
//            while((length = srcfis.read(buffer))!=-1){
//                fos.write(buffer,0,length);
//            }
//            HiLog.info(LABEL_LOG,"写入完成");
//            fos.close();
//        } catch (DataAbilityRemoteException e) {
//            e.printStackTrace();
//        }
//
//        srcfis.close();
//        callback.reply(res);
//    }

    public void saveVideo(String path, Callback callback) throws IOException {
        HiLog.info(LABEL_LOG,"开始"+StaticV.context.getCacheDir().getAbsolutePath());
        DataAbilityHelper helper=DataAbilityHelper.creator(StaticV.context);
        //声名一个要保存的值
        ValuesBucket values = new ValuesBucket();
        HiLog.info(LABEL_LOG,"helper");
        //比如http://xxx/xxx/文件名.文件类型
        String[] paths = path.split("/");
        //获取文件名
        String fileName = paths[paths.length-1];

        HiLog.info(LABEL_LOG,StaticV.context.getCacheDir().getAbsolutePath()+"/"+fileName);
        //获取cache目录下的下载文件的输入流
        FileInputStream srcfis = new FileInputStream(StaticV.context.getCacheDir().getAbsolutePath()+"/"+fileName);
        HiLog.info(LABEL_LOG,"fis");

        //通过spilt函数截取待创建的文件名
        values.putString(AVStorage.Downloads.DISPLAY_NAME, fileName.split("\\.")[0]);
        //通过spilt函数截取文件格式
        values.putString(AVStorage.Downloads.MIME_TYPE, "video/"+fileName.split("\\.")[1]);
        //向DataAbilityHelper中插入文件信息，插入成功后会返回文件的id
        try {
            int id = helper.insert(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, values);
            //通过id拼接文件的uri
            Uri targeruri = Uri.appendEncodedPathToUri(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
            //获取文件描述符
            FileDescriptor fd = helper.openFile(targeruri, "rw");
            //根据文件描述符获取输出流
            FileOutputStream fos = new FileOutputStream(fd);
            HiLog.info(LABEL_LOG,"fos");
            int length;
            byte[] buffer = new byte[1024];
            while((length = srcfis.read(buffer))!=-1){
                fos.write(buffer,0,length);
            }
            HiLog.info(LABEL_LOG,"写入完成");
            fos.close();
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }

        srcfis.close();
        callback.reply(fileName);
    }

//    public void uploadFile(String fileName,InputStream fileInputStream) {
//        try {
//
//            // 换行符
//            final String newLine = "\r\n";
//            final String boundaryPrefix = "--";
//            // 定义数据分隔线
//            String BOUNDARY = "========7d4a6d158c9";
//            // 服务器的域名
//            URL url = new URL("http://192.168.137.1:8003/x/user/upload");
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            // 设置为POST
//            conn.setRequestMethod("POST");
//            // 发送POST请求必须设置如下两行
//            conn.setDoOutput(true);
//            conn.setDoInput(true);
//            conn.setUseCaches(false);
//            // 设置请求头参数
//            //conn.setRequestProperty("connection", "Keep-Alive");
//            //conn.setRequestProperty("Charsert", "UTF-8");
//            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
//
//            OutputStream out = new DataOutputStream(conn.getOutputStream());
//
//            // 上传文件
//            File file = new File(fileName);
//            StringBuilder sb = new StringBuilder();
//            sb.append(boundaryPrefix);
//            sb.append(BOUNDARY);
//            sb.append(newLine);
//            // 文件参数,photo参数名可以随意修改
//            sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + fileName
//                    + "\"" + newLine);
//            sb.append("Content-Type:image/jpeg");
//            // 参数头设置完以后需要两个换行，然后才是参数内容
//            sb.append(newLine);
//            sb.append(newLine);
//
//            // 将参数头的数据写入到输出流中
//            out.write(sb.toString().getBytes());
//
//            // 数据输入流,用于读取文件数据
////            DataInputStream in = new DataInputStream(new FileInputStream(file));
//            DataInputStream in = new DataInputStream(fileInputStream);
//
//            byte[] bufferOut = new byte[1024];
//            int bytes = 0;
//            // 每次读1KB数据,并且将文件数据写入到输出流中
//            while ((bytes = in.read(bufferOut)) != -1) {
//                out.write(bufferOut, 0, bytes);
//            }
//            // 最后添加换行
//            out.write(newLine.getBytes());
//            in.close();
//
//            // 定义最后数据分隔线，即--加上BOUNDARY再加上--。
//            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine).getBytes();
//            // 写上结尾标识
//            out.write(end_data);
//            out.flush();
//            out.close();
//
//            // 定义BufferedReader输入流来读取URL的响应
//            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//            String line = null;
//            while ((line = reader.readLine()) != null) {
//                System.out.println(line);
//            }
//        } catch (Exception e) {
//            System.out.println("发送POST请求出现异常！" + e);
//            e.printStackTrace();
//        }
//    }

    @Override
    public void onStart(Intent intent) {
        HiLog.error(LABEL_LOG, "UtilServiceAbility::onStart");
        super.onStart(intent);
    }

    @Override
    public void onBackground() {
        super.onBackground();
        HiLog.info(LABEL_LOG, "UtilServiceAbility::onBackground");
    }

    @Override
    public void onStop() {
        super.onStop();
        HiLog.info(LABEL_LOG, "UtilServiceAbility::onStop");
    }

    @Override
    public void onCommand(Intent intent, boolean restart, int startId) {
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        return null;
    }

    @Override
    public void onDisconnect(Intent intent) {
    }
}